<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="前言之前也接触过node.js，但最近才想完全系统的入手实践node，因此想以狼书为着手点，开始入门node，以下其实更多的是看书后的总结与感悟。 最小功效原则：选择最适合的解决方案而不是最强的，语言的功效越弱，对于存储在语言中通的数据，我们能做的事情就越多。因此，语言结构越简单，进行数据分析与提取就越容易， Node.js的本质：是JavaScript运行时环境，构建在V8引擎之上，会最终转译成">
<meta property="og:type" content="article">
<meta property="og:title" content="nodejs">
<meta property="og:url" content="http://example.com/2021/09/25/node/node.js%E5%88%9D%E8%AF%86/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="前言之前也接触过node.js，但最近才想完全系统的入手实践node，因此想以狼书为着手点，开始入门node，以下其实更多的是看书后的总结与感悟。 最小功效原则：选择最适合的解决方案而不是最强的，语言的功效越弱，对于存储在语言中通的数据，我们能做的事情就越多。因此，语言结构越简单，进行数据分析与提取就越容易， Node.js的本质：是JavaScript运行时环境，构建在V8引擎之上，会最终转译成">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-09-25T04:18:39.000Z">
<meta property="article:modified_time" content="2021-11-03T08:20:13.482Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="node狼书">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://example.com/2021/09/25/node/node.js%E5%88%9D%E8%AF%86/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>nodejs | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/09/25/node/node.js%E5%88%9D%E8%AF%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          nodejs
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
    
              <time title="创建时间：2021-09-25 12:18:39" itemprop="dateCreated datePublished" datetime="2021-09-25T12:18:39+08:00">2021-09-25</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-11-03 16:20:13" itemprop="dateModified" datetime="2021-11-03T16:20:13+08:00">2021-11-03</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>之前也接触过node.js，但最近才想完全系统的入手实践node，因此想以狼书为着手点，开始入门node，以下其实更多的是看书后的总结与感悟。</p>
<p>最小功效原则：选择最适合的解决方案而不是最强的，语言的功效越弱，对于存储在语言中通的数据，我们能做的事情就越多。因此，语言结构越简单，进行数据分析与提取就越容易，</p>
<p>Node.js的本质：是JavaScript运行时环境，构建在V8引擎之上，会最终转译成C或者C++来执行，Node.js中的每个函数都是同步的，而I/O操作是异步的，所有由JS编写的函数I/O操作将会转义成C++的事件循环库来处理，隐藏了非阻塞I/O的具体细节，简化了并发编程模型。Node.js的目标是让并发编程更加地简单。 </p>
<p>Node.js是基于V8构建的，由其事件循环机制来分发I/O任务，最终工作线程会将任务放到线程池中执行，而事件循环只要等待执行结果就好了。在解决并发问题上，异步是最好的解决方案，其实就是可以类比为排队与叫号机制。</p>
<p>Node.js已经帮我们构建了类似的机制，写代码的过程就是取号的过程，由事件循环来接受处理，而真正执行操作的是具体线程池中的I/O任务。简化了并发编程，但也埋下了祸根。</p>
<p>Node.js的四个特点：适合构建web应用的、高性能的、简单的、可扩展的。</p>
<p>Node.js是基于CommonJS规范的实现，即每一个文件都是一个模块，每个模块内部代码的写法都必须遵守CommonJS规范，多文件调用的核心基于模块对外暴露接口和互相引用。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"Hello"</span>);</span><br><span class="line">    <span class="comment">//这里我们使用module.exports对外暴露一个匿名函数</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> hello = <span class="built_in">require</span>(<span class="string">'./hello_commonjs'</span>);</span><br><span class="line"><span class="comment">//这里通过require关键字来引用模块，由于在上面我们于模块中导出了一个匿名函数，所以可以直接调用。</span></span><br></pre></td></tr></table></figure>

<p>注：块作用域声明像let、const、function、class等在严格模式以外是不支持的，需要先在文件第一行加上use strict。</p>
<h1 id="更了不起的Node-js"><a href="#更了不起的Node-js" class="headerlink" title="更了不起的Node.js"></a>更了不起的Node.js</h1><h2 id="函数式编程"><a href="#函数式编程" class="headerlink" title="函数式编程"></a>函数式编程</h2><p>JS作为一个典型的多范式编程语言，最近其函数式编程概念开始流行，其要点如下：1、函数是第一等公民；2、函数柯里化：传递给函数一部分参数来调用2它，让它返回一个函数，从而去处理剩下的参数；3、为解决函数嵌套的问题，代码中使用了函数组合的方式，下面代码的calcAvgCost和flow函数都是典型的函数组合。</p>
<p>实例函数式编程代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> map = <span class="function"><span class="params">fn</span> =&gt;</span> <span class="function"><span class="params">array</span> =&gt;</span> array.map(fn);</span><br><span class="line"><span class="keyword">const</span> prop = <span class="function"><span class="params">key</span> =&gt;</span> <span class="function"><span class="params">object</span> =&gt;</span> object[key];</span><br><span class="line"><span class="keyword">const</span> reduce = <span class="function">(<span class="params">fn, initial</span>) =&gt;</span> <span class="function"><span class="params">array</span> =&gt;</span> array.reduce(fn, initial);</span><br><span class="line"><span class="keyword">const</span> add = <span class="function">(<span class="params">x, y</span>) =&gt;</span> x + y;</span><br><span class="line"><span class="keyword">const</span> sum = reduce(add, <span class="number">0</span>);</span><br><span class="line"><span class="keyword">const</span> filter = <span class="function"><span class="params">fn</span> =&gt;</span> <span class="function"><span class="params">array</span> =&gt;</span> array.filter(fn);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> average = <span class="function"><span class="params">items</span> =&gt;</span> (</span><br><span class="line">    items.length === <span class="number">0</span> . ? <span class="number">0</span> : sum(items) / items.length</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> flow = <span class="function">(<span class="params">...fns</span>) =&gt;</span> <span class="function"><span class="params">x</span> =&gt;</span> (</span><br><span class="line">	fns.reduce(<span class="function">(<span class="params">result, fn</span>) =&gt;</span> fn(result), x)</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> calcAvgCost = <span class="function">(<span class="params">items, filterFn = (</span>) =&gt;</span> <span class="literal">true</span>) =&gt; &#123;</span><br><span class="line">    flow(</span><br><span class="line">    	filter(filterFn),</span><br><span class="line">        map(prop(<span class="string">'price'</span>)),</span><br><span class="line">        average</span><br><span class="line">    )(items)</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//calcAvgCost函数的用法如下代码所示</span></span><br><span class="line"><span class="keyword">const</span> items = [</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">''</span>&#125;</span><br><span class="line">]</span><br><span class="line"><span class="keyword">const</span> avgCost = calcAvgCost(items);</span><br></pre></td></tr></table></figure>

<p>函数柯里化的相关定义与应用如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 函数柯里化及其通用封装</span></span><br><span class="line"><span class="comment">柯里化就是，</span></span><br><span class="line"><span class="comment">把原来的函数 adder(3,5,6,7,8,9) ==&gt; adder(3)(5)(6)(7)(8)(9)()；</span></span><br><span class="line"><span class="comment">那么这么做的好处是什么呢？</span></span><br><span class="line"><span class="comment">延迟计算，何时想要结果了，直接adder()就行了</span></span><br><span class="line"><span class="comment">通常也成为部分求值，给函数分步传递参数，逐步缩小函数的适用范围，逐步求解的过程。</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">如何实现柯里化函数</span></span><br><span class="line"><span class="comment">柯里化的定义，接收一部分参数，返回一个函数接收剩余参数，接收足够参数后，执行原函数。</span></span><br><span class="line"><span class="comment">我们已经知道了，当柯里化函数接收到足够参数后，就会执行原函数，</span></span><br><span class="line"><span class="comment">那么我们如何去确定何时达到足够的参数呢？</span></span><br><span class="line"><span class="comment">我们有两种思路：</span></span><br><span class="line"><span class="comment">1、通过函数的 length 属性，获取函数的形参个数，形参的个数就是所需的参数个数</span></span><br><span class="line"><span class="comment">2、在调用柯里化工具函数时，手动指定所需的参数个数</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="comment">/*通用版本：curry 函数的第一个参数是要动态创建柯里化的函数，余下的参数存储在 args 变量中。</span></span><br><span class="line"><span class="comment">执行 curry 函数返回的函数接收新的参数与 args 变量存储的参数合并，并把合并的参数传入给柯里化了的函数。 </span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">curry</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> args = <span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>, <span class="number">1</span>);</span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">		<span class="keyword">var</span> newArgs = args.concat(<span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>));</span><br><span class="line">        <span class="keyword">return</span> fn.apply(<span class="keyword">this</span>, newArgs);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/*bind函数；柯里化另一个典型的应用场景就是 bind 函数的实现。使用了函数柯里化的两个特点：参数复用和提前返回。*/</span></span><br><span class="line"><span class="built_in">Function</span>.prototype.bind = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="keyword">var</span> fn = <span class="keyword">this</span>;</span><br><span class="line">	<span class="keyword">var</span> args = <span class="built_in">Array</span>.prototye.slice.call(<span class="built_in">arguments</span>);</span><br><span class="line">	<span class="keyword">var</span> context = args.shift();</span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">		<span class="keyword">return</span> fn.apply(context, args.concat(<span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>)));</span><br><span class="line">	&#125;;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*优化版：实现add(1)(2)(3)();只有在输入()时才计算值 */</span></span><br><span class="line"><span class="keyword">const</span> currying = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> args = [];</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">arguments</span>.length === <span class="number">0</span>) &#123;</span><br><span class="line">             <span class="keyword">return</span> fn.apply(<span class="keyword">this</span>, args);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="built_in">Array</span>.prototype.push.apply(args, [].slice.call(<span class="built_in">arguments</span>));</span><br><span class="line">            <span class="comment">//args.push([].slice.call(arguments));//用slice将类数组转换成数组，在合并至args上。</span></span><br><span class="line">            <span class="comment">//Array.prototype.push()添加一个或多个元素到数组的末尾，并返回数组新的长度（length 属性值）。利用该方法合并两个参数数组</span></span><br><span class="line">            <span class="keyword">return</span> f;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> sum = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> ans = <span class="number">0</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="built_in">arguments</span>);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>;i &lt; <span class="built_in">arguments</span>.length; i++) &#123;</span><br><span class="line">        ans = ans + <span class="built_in">parseInt</span>(<span class="built_in">arguments</span>[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ans;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> sum1 = currying(sum);</span><br><span class="line"><span class="built_in">console</span>.log(sum(<span class="number">100</span>,<span class="number">200</span>))</span><br><span class="line"><span class="built_in">console</span>.log(sum1(<span class="number">100</span>, <span class="number">200</span>)(<span class="number">300</span>)(<span class="number">200</span>));</span><br><span class="line"><span class="built_in">console</span>.log(sum1());</span><br><span class="line"></span><br><span class="line"><span class="comment">/* </span></span><br><span class="line"><span class="comment">函数柯里化是把接受多个参数的函数转变成接受一个单一参数(最初函数的第一个参数),</span></span><br><span class="line"><span class="comment">并且返回接受余下的参数而且返回结果的新函数的技术柯里化其实本身是固定一个可以预期的参数，并返回一个特定的函数，</span></span><br><span class="line"><span class="comment">处理批特定的需求。这增加了函数的适用性，但同时也降低了函数的适用范围。</span></span><br><span class="line"><span class="comment">1、提高适用性</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="comment">//2、延迟执行：柯里化的另一个应用场景是延迟执行。不断的柯里化，累积传入的参数，最后执行。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/*3、固定易变参数:柯里化特性决定了它这应用场景。</span></span><br><span class="line"><span class="comment">提前把易变因素，传参固定下来，生成一个更明确的应用函数。最典型的代表应用，是bind函数用以固定this这个易变对象。</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="comment">/*已知 fn 为一个预定义函数，实现函数 curryIt，调用之后满足如下条件：</span></span><br><span class="line"><span class="comment">1、返回一个函数 a，a 的 length 属性值为 1（即显式声明 a 接收一个参数）</span></span><br><span class="line"><span class="comment">2、调用 a 之后，返回一个函数 b, b 的 length 属性值为 1</span></span><br><span class="line"><span class="comment">3、调用 b 之后，返回一个函数 c, c 的 length 属性值为 1</span></span><br><span class="line"><span class="comment">4、调用 c 之后，返回的结果与调用 fn 的返回值一致</span></span><br><span class="line"><span class="comment">5、fn 的参数依次为函数 a, b, c 的调用参数 */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">curryIt</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> a = <span class="function"><span class="keyword">function</span>(<span class="params">s1</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> b = <span class="function"><span class="keyword">function</span>(<span class="params">s2</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">let</span> c = <span class="function"><span class="keyword">function</span>(<span class="params">s3</span>) </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> fn(s1, s2, s3);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> c;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> b;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> a;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="单线程"><a href="#单线程" class="headerlink" title="单线程"></a>单线程</h2><p>单线程十分脆弱，随便一点异常就容易挂掉，但Node.js就是单线程的，却再线上高可用的项目中被频繁运用以应对并发，关键在于使用的方法。单线程的使用要点：1、单个应用实例可以适当捕获异常。2、单个应用崩溃后，用PM2重启；3、利用多核集群同时在一台服务器上启动多个实例；4、多台服务器可做多个集群。</p>
<h3 id="异常捕获"><a href="#异常捕获" class="headerlink" title="异常捕获"></a>异常捕获</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"><span class="keyword">const</span> Koa = <span class="built_in">require</span>(<span class="string">'koa'</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> Koa();</span><br><span class="line"></span><br><span class="line">app.use(<span class="function"><span class="params">ctx</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (ctx.path == <span class="string">'/good'</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> ctx.body = <span class="string">'good'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    fs.readFile(<span class="string">'somefile.txt'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">err, data</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (err) <span class="keyword">throw</span> err;</span><br><span class="line">        <span class="built_in">console</span>.log(data);</span><br><span class="line">        </span><br><span class="line">        ctx.body = <span class="string">'Hello Koa'</span>;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">            <span class="comment">//这里捕获不到readCallback函数抛出的异常</span></span><br><span class="line">            <span class="built_in">console</span>.log(e);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'离开try/catch'</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">process.on(<span class="string">'uncaughtException'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">err</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(err);</span><br><span class="line">&#125;)</span><br><span class="line">app.listen(<span class="number">3000</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//使用process.on('uncaughtException', function (err) &#123;&#125;)可以捕获异常并避免接口崩溃.</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">在fs.readFile的回调中加入try、catch后，当读取文件遇到异常时，就会直接抛出，而异常会被try、catch捕获，当前线程就不会因为异常而意外结束。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>异常捕获的注意事项：1、Node.js中同步代码才能够捕获异常，promise的处理需要使用Promise的异常处理方法。2、try、catch会影响性能，因此也要谨慎使用。</p>
<p>Node中有专门负责进程崩溃后应用自动重启的模块，名为forever；现在通常使用PM2来代替。</p>
<h3 id="集群"><a href="#集群" class="headerlink" title="集群"></a>集群</h3><p>小集群：现在的单台服务器大多是多核的，使用Cluster集群模块专门用于解决多核并发问题。</p>
<p>Nginx或HAProxy等集群都是一主多从的，主机的端口通过负载均衡算法将请求转发到Slave机器上，在一台机器上启动多个实例，原理也是类似。</p>
<p>这里通常都使用PM2进行统一的管理。</p>
<p>大集群：多台机器进行集群处理，同时通过负载均衡将流量分发到各个机器上，通过消除单点故障提升应用系统的可用性。常见的有Nginx、HAProxy、Tengine。</p>
<p>前端的所有请求都会落在负载层，再由负载层转发到负载中可用节点的服务器上。</p>
<h2 id="异步与回调"><a href="#异步与回调" class="headerlink" title="异步与回调"></a>异步与回调</h2><p>JavaScript现在通常使用Promise、async函数来进行回调地狱的解决，包括generator特性。</p>
<p>异步解决的处理中，首选async函数，其次使用Promise，Promise可以很好地价于callback与async。</p>
<h2 id="转译"><a href="#转译" class="headerlink" title="转译"></a>转译</h2><p>使用ES.next的特性进行开发，在生成环境里使用转译工具将ES.next特性转译为ES5。转译工具包括：babei、TypeScript、Traceur。</p>
<p>Delegate</p>
<p>在JS中可以将一个对象的方法、属性等委托给另一个对象。KOA的上下文对象ctx可以访问一些request和response上的方法、属性，原因在于request或者respomse上的方法、属性被委托给了ctx对象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> delegate = <span class="built_in">require</span>(<span class="string">'delegates'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> proto = &#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line">delegate(proto, <span class="string">'response'</span>).method(<span class="string">'redirect'</span>)...access(<span class="string">'body'</span>)...</span><br><span class="line"><span class="comment">//将上面的代码委托给response的属性</span></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span>(<span class="params">ctx, next</span>) </span>&#123;</span><br><span class="line">    ctx.body = <span class="string">'xxx'</span>;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>Only</p>
<p>在KOA的源码中总能看到toJSON()方法的实现，代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">toJSON() &#123;</span><br><span class="line">    <span class="keyword">return</span> only(<span class="keyword">this</span>, [</span><br><span class="line">        <span class="string">'method'</span>,</span><br><span class="line">        <span class="string">'url'</span>,</span><br><span class="line">        <span class="string">'header'</span></span><br><span class="line">    ])</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//这里的only是一个node.js模块，用于返回对象的白名单属性，尤其适用于类的方法非常多，但只想暴露部分属性的情况。</span></span><br></pre></td></tr></table></figure>


    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2021/09/25/node/node.js%E5%88%9D%E8%AF%86/" title="nodejs">http://example.com/2021/09/25/node/node.js初识/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/node%E7%8B%BC%E4%B9%A6/" rel="tag"># node狼书</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/09/24/node/%E6%95%B0%E6%8D%AE%E5%BA%93/" rel="prev" title="MongoDB数据库">
      <i class="fa fa-chevron-left"></i> MongoDB数据库
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/09/28/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/%E5%A4%A7%E8%AF%9D%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" rel="next" title="大话数据结构">
      大话数据结构 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#更了不起的Node-js"><span class="nav-number">2.</span> <span class="nav-text">更了不起的Node.js</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#函数式编程"><span class="nav-number">2.1.</span> <span class="nav-text">函数式编程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#单线程"><span class="nav-number">2.2.</span> <span class="nav-text">单线程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#异常捕获"><span class="nav-number">2.2.1.</span> <span class="nav-text">异常捕获</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#集群"><span class="nav-number">2.2.2.</span> <span class="nav-text">集群</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#异步与回调"><span class="nav-number">2.3.</span> <span class="nav-text">异步与回调</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#转译"><span class="nav-number">2.4.</span> <span class="nav-text">转译</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

